<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style type="text/css">
        .kuang{
            width: 1210px;
            margin: auto;
        }
        h1{
            color:red;
            text-align: center;
        }
        .nav{
            margin-bottom: 10px;
        }
        a{
            text-decoration: none;
            color: gray;
        }
        a:hover{
            color: red;
        }
        .content{
            display: flex;
            border: 3px solid red;
        }
        .column{
            flex-grow: 1;
            border: 1px solid gray;
            margin: 10px;
            padding: 10px;
        }
        p{
            margin:0;
            padding: 5px;
        }
        b{ color:red;}
    </style>
    <title>分页显示成语</title>
</head>
<body>
<h1>分页显示成语</h1>
<div class='kuang'>
    <div class='nav'><?php
        echo "\n";
        $db = new PDO('mysql:host=localhost;dbname=db', 'root', '12qwas');
        $total=$db->query("select count(1) from chengyu")->fetchColumn();//总的成语个数
        $lanNumber=5; //分栏的个数
        $chengyuCountPerLan=10;//每个分栏成语的个数
        $pageSize=$lanNumber*$chengyuCountPerLan;//一个页面上显示成语的个数
        $totalPages=(int)($total/$pageSize)+($total%$pageSize==0?0:1);//总的页面数
        //获取用户要显示的当前页面的页码
        @$currentPge = (int)$_GET["page"];//接受的参数都是字符串类型的数据
        if($currentPge<1)$currentPge=1;
        else if($currentPge>$totalPages)$currentPge=$totalPages;
        $n=15; //当前显示的页面前后数字导航超链接的个数
        $begin=$currentPge-$n;//页面导航的起始页码
        $over=$currentPge+$n;//页面导航的终止页码
        if($begin<1){
            $begin=1;
            $over=2*$n+1;
            if($over>$totalPages)$over=$totalPages;
        }else if($over>$totalPages){
            $over=$totalPages;
            $begin=$totalPages-2*$n;
            if($begin<1)$begin=1;
        }
        for($i=$begin; $i<=$over; ++$i){
            if($i==$currentPge)echo "\t\t<b>$i</b>\n";
            else echo "\t\t<a href='?page=$i'>$i</a>\n";
        }
        echo "\t</div>\n";
        echo "\t<div class='content'>\n";
        $ps = $db->prepare("select cy from chengyu limit ?, ?");
        $ps->bindValue(1, ($currentPge-1)*$pageSize, PDO::PARAM_INT);
        $ps->bindValue(2, $pageSize, PDO::PARAM_INT);
        $ps->execute();
        for($i=0;$i<$lanNumber;++$i){
            echo "\t\t<div class='column'>\n";
            for($j=0;$j<$chengyuCountPerLan;++$j){
                echo "\t\t\t<p>",$ps->fetchColumn(),"</p>\n";
            }
            echo "\t\t</div>\n";
        } ?>
    </div>
</div>
</body>
</html>
